// scripts/scan-components.js - 智能双向扫描版
const fs = require('fs')
const path = require('path')

// 配置
const CONFIG = {
  componentsDir: path.join(__dirname, '../src/components/global'),
  demoDir: path.join(__dirname, '../src/pages/demo'),
  componentPrefix: 'C_',
  componentEntryFile: 'index.vue',
  formats: {
    json: path.join(__dirname, '_data/components.json'),
    js: path.join(__dirname, '_data/components.js'),
  }
}

// 组件元信息配置
const COMPONENT_META = {
  'C_Header': {
    description: '统一头部导航组件，支持返回和标题',
    icon: 'i-mdi-page-layout-header',
    color: '#4ecdc4',
    category: 'navigation'
  },
  'C_Icon': {
    description: '通用图标组件，支持多种图标库',
    icon: 'i-mdi-palette',
    color: '#ff6b6b',
    category: 'general'
  },
  'C_Layout': {
    description: '页面布局组件，提供统一的页面结构',
    icon: 'i-mdi-view-dashboard-outline',
    color: '#45b7d1',
    category: 'layout'
  },
  'C_Tabbar': {
    description: '底部标签栏组件，支持徽章和自定义图标',
    icon: 'i-mdi-tab',
    color: '#26d0ce',
    category: 'navigation'
  },
  'C_Title': {
    description: '页面标题组件，支持多级标题',
    icon: 'i-mdi-format-title',
    color: '#a8e6cf',
    category: 'general'
  }
}

const DEFAULT_META = {
  description: '组件描述',
  icon: 'i-mdi-cube-outline',
  color: '#6366f1',
  category: 'general'
}

const COLORS = [
  '#ff6b6b', '#4ecdc4', '#45b7d1', '#26d0ce', '#a8e6cf', '#ffd93d',
  '#ff6b9d', '#6c5ce7', '#fd79a8', '#00cec9', '#74b9ff', '#0984e3',
  '#e17055', '#00b894', '#fdcb6e', '#a29bfe'
]

// 工具函数
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const i = Math.floor(Math.log(bytes) / Math.log(1024))
  const sizes = ['B', 'KB', 'MB']
  return Math.round(bytes / Math.pow(1024, i) * 100) / 100 + ' ' + sizes[i]
}

const getDirectorySize = (dirPath) => {
  try {
    let totalSize = 0
    const files = fs.readdirSync(dirPath)
    
    files.forEach(file => {
      const filePath = path.join(dirPath, file)
      const stats = fs.statSync(filePath)
      
      if (stats.isFile()) {
        totalSize += stats.size
      } else if (stats.isDirectory()) {
        totalSize += getDirectorySize(filePath)
      }
    })
    
    return formatFileSize(totalSize)
  } catch {
    return 'unknown'
  }
}

// 第1步：扫描demo目录
const scanDemoDirectories = () => {
  if (!fs.existsSync(CONFIG.demoDir)) return []
  
  try {
    return fs.readdirSync(CONFIG.demoDir)
      .map(dirName => {
        const indexPath = path.join(CONFIG.demoDir, dirName, 'index.vue')
        return {
          dirName,
          hasIndexFile: fs.existsSync(indexPath),
          fullPath: `/pages/demo/${dirName}/index`,
          absolutePath: indexPath
        }
      })
      .filter(demo => demo.hasIndexFile) // 只保留有index.vue的目录
  } catch (error) {
    console.warn(`扫描demo目录失败: ${error.message}`)
    return []
  }
}

// 第2步：智能匹配算法
const generateSearchKeys = (componentName) => {
  // C_Icon -> ['icon', 'c-icon', 'c_icon']
  const baseName = componentName.replace(/^C_/, '').toLowerCase()
  
  return [
    baseName,                           // icon
    baseName.replace(/_/g, '-'),        // icon (如果有下划线)
    `c-${baseName}`,                    // c-icon  
    `c_${baseName}`,                    // c_icon
    componentName.toLowerCase()         // c_icon
  ]
}

const calculateMatchScore = (demoDir, searchKeys) => {
  let score = 0
  
  searchKeys.forEach(key => {
    if (demoDir === key) {
      score = Math.max(score, 1.0) // 完全匹配
    } else if (demoDir.endsWith(`-${key}`)) {
      score = Math.max(score, 0.9) // 后缀匹配 (01-icon)
    } else if (demoDir.includes(key)) {
      score = Math.max(score, 0.7) // 包含匹配
    }
  })
  
  return score
}

const createComponentMatcher = (demoDirs) => {
  return (componentName) => {
    const searchKeys = generateSearchKeys(componentName)
    
    let bestMatch = null
    let highestScore = 0
    
    demoDirs.forEach(demo => {
      const score = calculateMatchScore(demo.dirName, searchKeys)
      if (score > highestScore) {
        highestScore = score
        bestMatch = { ...demo, matchScore: score }
      }
    })
    
    return highestScore > 0.5 ? bestMatch : null // 设置最低匹配阈值
  }
}

// 主要扫描函数
const scanComponents = () => {
  if (!fs.existsSync(CONFIG.componentsDir)) {
    throw new Error(`组件目录不存在: ${CONFIG.componentsDir}`)
  }

  try {
    const items = fs.readdirSync(CONFIG.componentsDir)
    
    const componentDirs = items.filter(item => {
      if (!item.startsWith(CONFIG.componentPrefix)) return false
      
      const itemPath = path.join(CONFIG.componentsDir, item)
      const stats = fs.statSync(itemPath)
      
      if (!stats.isDirectory()) return false
      
      const indexFile = path.join(itemPath, CONFIG.componentEntryFile)
      return fs.existsSync(indexFile)
    }).sort()
    
    const components = componentDirs.map((dirName, index) => {
      const componentPath = path.join(CONFIG.componentsDir, dirName)
      const meta = COMPONENT_META[dirName] || {
        ...DEFAULT_META,
        description: `${dirName} 组件`,
        color: COLORS[index % COLORS.length]
      }
      
      return {
        id: dirName.toLowerCase(),
        name: dirName,
        order: String(index + 1).padStart(2, '0'),
        path: '', // 待智能匹配填充
        filePath: `@/components/global/${dirName}`,
        entryFile: `@/components/global/${dirName}/${CONFIG.componentEntryFile}`,
        dirName,
        description: meta.description,
        icon: meta.icon,
        color: meta.color,
        category: meta.category,
        hasDemo: false, // 待智能匹配填充
        status: 'developing', // 待智能匹配填充
        scannedAt: new Date().toISOString(),
        fileSize: getDirectorySize(componentPath),
        // 智能匹配相关信息
        matchScore: 0,
        possibleDemoPaths: [], // 可能的匹配路径，用于管理页面选择
        autoDetected: false // 标识是否为自动检测
      }
    })
    
    return applySmartDemoDetection(components)
  } catch (error) {
    throw new Error(`扫描组件失败: ${error.message}`)
  }
}

// 第3步：智能demo检测
const applySmartDemoDetection = (components) => {
  const availableDemos = scanDemoDirectories()
  const matcher = createComponentMatcher(availableDemos)
  
  return components.map(component => {
    const searchKeys = generateSearchKeys(component.name)
    
    // 找到所有可能的匹配（用于管理页面选择）
    const possibleMatches = availableDemos
      .map(demo => ({
        ...demo,
        score: calculateMatchScore(demo.dirName, searchKeys)
      }))
      .filter(demo => demo.score > 0.3)
      .sort((a, b) => b.score - a.score)
      .slice(0, 3) // 最多保留3个候选
    
    // 获取最佳匹配
    const bestMatch = matcher(component.name)
    
    return {
      ...component,
      hasDemo: !!bestMatch,
      status: bestMatch ? 'completed' : 'developing',
      path: bestMatch ? bestMatch.fullPath : generateDefaultPath(component.name),
      matchScore: bestMatch ? bestMatch.matchScore : 0,
      possibleDemoPaths: possibleMatches.map(m => ({
        path: m.fullPath,
        dirName: m.dirName,
        score: m.score,
        label: `${m.dirName} (匹配度: ${Math.round(m.score * 100)}%)`
      })),
      autoDetected: !!bestMatch,
      detectedDemoDir: bestMatch ? bestMatch.dirName : null
    }
  })
}

const generateDefaultPath = (componentName) => {
  const kebabName = componentName.toLowerCase().replace(/^c_/, '').replace(/_/g, '-')
  return `/pages/demo/${kebabName}/index`
}

// 生成数据文件
const generateFiles = (components) => {
  const outputDir = path.dirname(CONFIG.formats.json)
  if (!fs.existsSync(outputDir)) {
    fs.mkdirSync(outputDir, { recursive: true })
  }
  
  const data = {
    version: '1.0.0',
    generatedAt: new Date().toISOString(),
    scanMode: 'smart-detection',
    total: components.length,
    completed: components.filter(c => c.status === 'completed').length,
    developing: components.filter(c => c.status === 'developing').length,
    categories: getCategoryStats(components),
    autoDetected: components.filter(c => c.autoDetected).length,
    manualConfig: components.filter(c => !c.autoDetected && c.hasDemo).length,
    components
  }
  
  // 生成 JSON
  fs.writeFileSync(CONFIG.formats.json, JSON.stringify(data, null, 2), 'utf8')
  
  // 生成 JS
  const jsContent = `// Auto-generated at ${data.generatedAt}
export default ${JSON.stringify(data, null, 2)}

export const { components, total, completed, developing, categories } = ${JSON.stringify(data, null, 2)}
`
  fs.writeFileSync(CONFIG.formats.js, jsContent, 'utf8')
  
  return data
}

const getCategoryStats = (components) => {
  return components.reduce((stats, component) => {
    const category = component.category || 'general'
    stats[category] = (stats[category] || 0) + 1
    return stats
  }, {})
}

// 精致的输出展示
const displayHeader = () => {
  console.log('┌─────────────────────────────────────────────────────────────┐')
  console.log('│                 🤖 智能组件扫描器                           │') 
  console.log('├─────────────────────────────────────────────────────────────┤')
  console.log(`│ 📁 组件目录: ${CONFIG.componentsDir.replace(process.cwd(), '.')}`)
  console.log(`│ 🎯 演示目录: ${CONFIG.demoDir.replace(process.cwd(), '.')}`)
  console.log(`│ 🔍 前缀规则: ${CONFIG.componentPrefix}`)
  console.log('└─────────────────────────────────────────────────────────────┘')
}

const displayScanProgress = (components, demoDirs) => {
  console.log('\n🔍 智能扫描进度...')
  console.log('├─ 正在扫描组件目录...')
  console.log(`├─ 找到 ${components.length} 个组件`)
  console.log('├─ 正在扫描演示目录...')
  console.log(`├─ 找到 ${demoDirs.length} 个演示页面`)
  console.log('├─ 正在执行智能匹配...')
  console.log('└─ 扫描完成!\n')
}

const displayComponentList = (components) => {
  console.log('📋 智能匹配结果:')
  console.log('┌────┬──────────────┬──────────────┬──────────────┬──────────────┐')
  console.log('│ #  │ 组件名称     │ 匹配演示     │ 状态         │ 匹配度       │')
  console.log('├────┼──────────────┼──────────────┼──────────────┼──────────────┤')
  
  components.forEach((component) => {
    const status = component.hasDemo ? '✅ 已完成' : '🚧 开发中'
    const demoDir = component.detectedDemoDir || '无匹配'
    const matchScore = component.matchScore > 0 ? `${Math.round(component.matchScore * 100)}%` : '0%'
    
    console.log(`│ ${component.order} │ ${component.name.padEnd(12)} │ ${demoDir.padEnd(12)} │ ${status.padEnd(12)} │ ${matchScore.padEnd(12)} │`)
  })
  
  console.log('└────┴──────────────┴──────────────┴──────────────┴──────────────┘')
}

const displayMatchingDetails = (components) => {
  console.log('\n🎯 匹配详情:')
  
  const autoMatched = components.filter(c => c.autoDetected)
  const unmatched = components.filter(c => !c.hasDemo)
  
  if (autoMatched.length > 0) {
    console.log('✅ 自动匹配成功:')
    autoMatched.forEach(c => {
      console.log(`   • ${c.name} → ${c.detectedDemoDir} (${Math.round(c.matchScore * 100)}%)`)
    })
  }
  
  if (unmatched.length > 0) {
    console.log('⚠️  未找到匹配:')
    unmatched.forEach(c => {
      console.log(`   • ${c.name} → 建议创建: ${c.path.replace('/pages/demo/', '').replace('/index', '')}`)
      if (c.possibleDemoPaths.length > 0) {
        console.log(`     可选路径: ${c.possibleDemoPaths.map(p => p.dirName).join(', ')}`)
      }
    })
  }
}

const displayStatistics = (data) => {
  console.log('\n📊 扫描统计:')
  console.log('┌─────────────────────────────────────────────────────────────┐')
  console.log(`│ 📦 组件总数:   ${String(data.total).padStart(3)} 个`)
  console.log(`│ ✅ 已完成:     ${String(data.completed).padStart(3)} 个`)
  console.log(`│ 🚧 开发中:     ${String(data.developing).padStart(3)} 个`)
  console.log(`│ 🤖 自动匹配:   ${String(data.autoDetected).padStart(3)} 个`)
  console.log('└─────────────────────────────────────────────────────────────┘')
}

const displayOutputFiles = (data) => {
  console.log('\n📁 生成的数据文件:')
  const jsonPath = CONFIG.formats.json.replace(process.cwd(), '.')
  const jsPath = CONFIG.formats.js.replace(process.cwd(), '.')
  
  console.log(`✅ JSON 数据文件: ${jsonPath}`)
  console.log(`✅ JS 模块文件:   ${jsPath}`)
}

const displayFooter = () => {
  const now = new Date().toLocaleString('zh-CN')
  console.log('\n┌─────────────────────────────────────────────────────────────┐')
  console.log(`│ 🎉 智能扫描完成! 时间: ${now}              │`)
  console.log('│ 💡 提示: 可在管理页面中调整未匹配的组件路径               │')
  console.log('└─────────────────────────────────────────────────────────────┘')
}

// 主函数
const main = () => {
  const args = process.argv.slice(2)
  const watch = args.includes('--watch') || args.includes('-w')
  
  try {
    displayHeader()
    
    const demoDirs = scanDemoDirectories()
    const components = scanComponents()
    
    displayScanProgress(components, demoDirs)
    displayComponentList(components)
    displayMatchingDetails(components)
    
    const data = generateFiles(components)
    displayStatistics(data)
    displayOutputFiles(data)
    displayFooter()
    
    if (watch) {
      console.log('\n👀 监听模式已启动，等待文件变化...')
      fs.watchFile(CONFIG.componentsDir, { interval: 2000 }, () => {
        console.log('\n🔄 检测到组件变化，重新扫描...')
        main()
      })
      fs.watchFile(CONFIG.demoDir, { interval: 2000 }, () => {
        console.log('\n🔄 检测到演示变化，重新扫描...')
        main()
      })
    }
    
    return true
  } catch (error) {
    console.log('\n┌─────────────────────────────────────────────────────────────┐')
    console.log('│                        ❌ 扫描失败                          │')
    console.log('├─────────────────────────────────────────────────────────────┤')
    console.log(`│ 错误: ${error.message}`)
    console.log('└─────────────────────────────────────────────────────────────┘')
    return false
  }
}

// 导出和执行
if (require.main === module) {
  main()
}

module.exports = { scanComponents, generateFiles, CONFIG }